package com.authine.cloudpivot.ext.converter;

import cn.hutool.core.date.DateUtil;
import com.authine.cloudpivot.ext.constants.OrganizationNameConstant;
import com.authine.cloudpivot.ext.dto.CustomerGoodsDTO;
import com.authine.cloudpivot.ext.dto.VendorOrderDTO;
import com.authine.cloudpivot.ext.enums.IfYesStatusEnum;
import com.authine.cloudpivot.ext.enums.InvoiceStatusEnum;
import com.authine.cloudpivot.ext.enums.OrderTimeRangeEnum;
import com.authine.cloudpivot.ext.utils.StringUtils;
import com.sun.org.apache.xpath.internal.operations.And;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;
import java.util.Optional;

/**
 * @author wangning
 */
public class CustomerOrderConverter {

    /**
     * 拼接sql查询语句
     * @param customerGoodsDTO
     * @param whereBuilder
     * @param queryParams
     */
    public static void goodsSplicer(CustomerGoodsDTO customerGoodsDTO, StringBuilder whereBuilder, Map<String, Object> queryParams) {
        //查询条件判断


        if (StringUtils.isNotBlank(customerGoodsDTO.getOrderCustomerGoodsStatus())){
            whereBuilder.append(" and a.order_customer_goods_status = :orderCustomerGoodsStatus");
            queryParams.put("orderCustomerStatus", customerGoodsDTO.getOrderCustomerGoodsStatus());
        }

        //查询条件判断
        if (StringUtils.isNotBlank(customerGoodsDTO.getAddress())){
            whereBuilder.append(" and a.address like :address");
            queryParams.put("address", filedToLike(customerGoodsDTO.getAddress()));

        }


        if (StringUtils.isNotBlank(customerGoodsDTO.getPlaceOrderFullname())){
            whereBuilder.append(" and a.place_order_fullname like :placeOrderFullname");
            queryParams.put("placeOrderFullname", filedToLike(customerGoodsDTO.getPlaceOrderFullname()));
        }

        if (StringUtils.isNotBlank(customerGoodsDTO.getErpPo())){
            whereBuilder.append(" and a.erp_po like :erpPo");
            queryParams.put("erpPo", filedToLike(customerGoodsDTO.getErpPo()));
        }


        if (StringUtils.isNotBlank(customerGoodsDTO.getName())){
            whereBuilder.append(" and name like :name");
            queryParams.put("name", filedToLike(customerGoodsDTO.getName()));
        }

        if (StringUtils.isNotBlank(customerGoodsDTO.getBrand())){
            whereBuilder.append(" and brand like :brand");
            queryParams.put("brand", filedToLike(customerGoodsDTO.getBrand()));
        }



        if (StringUtils.isNotBlank(customerGoodsDTO.getModel())){
            whereBuilder.append(" and model like :model");
            queryParams.put("model", filedToLike(customerGoodsDTO.getModel()));
        }

        if (StringUtils.isNotBlank(customerGoodsDTO.getSku())){
            whereBuilder.append(" and sku like :sku");
            queryParams.put("sku", filedToLike(customerGoodsDTO.getSku()));
        }
        if (StringUtils.isNotBlank(customerGoodsDTO.getId())){
            whereBuilder.append(" and id like :id");
            queryParams.put("id", filedToLike(customerGoodsDTO.getId()));
        }

        //判断照片是否上传
        if (!ObjectUtils.isEmpty(customerGoodsDTO.getIfUploadImage())){

            if (IfYesStatusEnum.checkYes(customerGoodsDTO.getIfUploadImage())){
                whereBuilder.append(" and ifStatus =1 and JSON_LENGTH(images)>0" );
            }else {
                whereBuilder.append("  AND ( ifStatus =0 OR CASE WHEN JSON_VALID( images) THEN JSON_LENGTH(images) =0 ELSE NULL END ) " );
            }
        }
        //判断是否补充澄清
        if (!ObjectUtils.isEmpty(customerGoodsDTO.getIfClarifyTips())){
            if (IfYesStatusEnum.checkYes(customerGoodsDTO.getIfClarifyTips())){
                whereBuilder.append(" and (clarify_tips is not null and clarify_tips != '') " );
            } else {
                whereBuilder.append(" and (clarify_tips is null or clarify_tips = '') " );
            }
        }


        //下单时间
        if (CollectionUtils.isNotEmpty(customerGoodsDTO.getPlaceOrderTime())){
            whereBuilder.append(" and d.place_order_time >= :startTime  and d.place_order_time <= :endTime");
            queryParams.put("startTime", customerGoodsDTO.getPlaceOrderTime().get(0));
            queryParams.put("endTime", customerGoodsDTO.getPlaceOrderTime().get(1));
        }

        //判断是否开票
        if (!ObjectUtils.isEmpty(customerGoodsDTO.getInvoiceStatus())){
            String sqlCondition="is null and a.invoice_numbers =''";
            //已开票
            boolean flag = InvoiceStatusEnum.checkInvoiceStatus(customerGoodsDTO.getInvoiceStatus());
            if (flag){
                sqlCondition="is not null and a.invoice_numbers !=''";
            }
            whereBuilder.append(" and a.invoice_numbers ").append(sqlCondition);
        }



        //中标供应商->供应商组织名称
        if (StringUtils.isNotBlank(customerGoodsDTO.getVendorOrganizationName())){
            whereBuilder.append(" and vendor_organization_name like :vendorOrganizationName");
            queryParams.put("vendorOrganizationName", filedToLike(customerGoodsDTO.getVendorOrganizationName()));
        }

        Integer placeSelect = customerGoodsDTO.getPlaceOrderTimeSelect();

        //7天内外条件筛选
        if (!ObjectUtils.isEmpty(placeSelect)){
            Date date = new Date();
            Date dateTime = DateUtil.offsetDay(date, -7);
            String formatDateTime = DateUtil.formatDateTime(dateTime);
            //如果是大于7天,7天以外
            if (OrderTimeRangeEnum.checkGreater(placeSelect)){
                whereBuilder.append(" and a.place_order_time < :formatDateTime");
            } else {
                whereBuilder.append(" and a.place_order_time >= :formatDateTime");
            }
            queryParams.put("formatDateTime",formatDateTime);
        }
        //已取消不需要展示
        whereBuilder.append(" and (");
        whereBuilder.append(" (a.order_customer_status  = 'UpcomingConfirm'  and a.enabled = 0)");
        whereBuilder.append(" or (a.order_customer_status = 'DoneDelivery' and after_sale='售后中') ");
        whereBuilder.append(" and a.enabled = 0 ");
        whereBuilder.append(" OR a.order_customer_status='DoneDelivery' ");
        whereBuilder.append(" OR a.order_customer_status='Done' )");
        whereBuilder.append(" order by a.place_order_time desc ");
    }


    /**
     * 拼接sql查询语句
     * @param vendorOrderDTO
     * @param whereBuilder
     * @param queryParams
     */
    public static void orderSplicer(VendorOrderDTO vendorOrderDTO, StringBuilder whereBuilder, Map<String, Object> queryParams) {
        //筛选牧原组织信息
        String organizationName= Optional.ofNullable(vendorOrderDTO.getOrganizationName()).orElse(OrganizationNameConstant.MY_ORGANIZATION_NAME);

        whereBuilder.append(" and a.organization_name = :organizationName");
        queryParams.put("organizationName", organizationName);


        //查询条件判断
        if (StringUtils.isNotBlank(vendorOrderDTO.getOrderCustomerStatus())){
            whereBuilder.append(" and a.order_customer_status = :orderCustomerStatus");
            queryParams.put("orderCustomerStatus", vendorOrderDTO.getOrderCustomerStatus());
        }

        //查询条件判断
        if (StringUtils.isNotBlank(vendorOrderDTO.getAddress())){
            whereBuilder.append(" and a.address like :address");
            queryParams.put("address", CustomerOrderConverter.filedToLike(vendorOrderDTO.getAddress()));

        }


        if (StringUtils.isNotBlank(vendorOrderDTO.getPlaceOrderFullname())){
            whereBuilder.append(" and a.place_order_fullname like :placeOrderFullname");
            queryParams.put("placeOrderFullname", CustomerOrderConverter.filedToLike(vendorOrderDTO.getPlaceOrderFullname()));
        }

        if (StringUtils.isNotBlank(vendorOrderDTO.getErpPo())){
            whereBuilder.append(" and a.erp_po like :erpPo");
            queryParams.put("erpPo", CustomerOrderConverter.filedToLike(vendorOrderDTO.getErpPo()));

        }

        //下单时间
        if (CollectionUtils.isNotEmpty(vendorOrderDTO.getPlaceOrderTime())){
            whereBuilder.append(" and a.createdTime >= :startTime  and a.createdTime <= :endTime");
            queryParams.put("startTime", vendorOrderDTO.getPlaceOrderTime().get(0));
            queryParams.put("endTime", vendorOrderDTO.getPlaceOrderTime().get(1));
        }


        Integer placeSelect = vendorOrderDTO.getPlaceOrderTimeSelect();

        if (!ObjectUtils.isEmpty(placeSelect)){
            Date date = new Date();
            Date dateTime = DateUtil.offsetDay(date, -7);
            String formatDateTime = DateUtil.formatDateTime(dateTime);
            //如果是大于7天,7天以外
            if (OrderTimeRangeEnum.checkGreater(placeSelect)){
                whereBuilder.append(" and a.createdTime < :formatDateTime");
            } else {
                whereBuilder.append(" and a.createdTime >= :formatDateTime");
            }
            queryParams.put("formatDateTime",formatDateTime);
        }

        //判断是否开票
        if (!ObjectUtils.isEmpty(vendorOrderDTO.getInvoiceStatus())){
            String sqlCondition="is null and a.invoice_numbers =''";
            //已开票
            boolean flag = InvoiceStatusEnum.checkInvoiceStatus(vendorOrderDTO.getInvoiceStatus());
            if (flag){
                sqlCondition="is not null and a.invoice_numbers !=''";
            }
            whereBuilder.append(" and a.invoice_numbers ").append(sqlCondition);
        }

        //已取消不需要展示
        whereBuilder.append(" and ( ");
        whereBuilder.append(" (a.order_customer_status  = 'UpcomingConfirm'  and a.enabled = 0)");
        whereBuilder.append(" or (a.order_customer_status = 'DoneDelivery' and after_sale='售后中') ");
        whereBuilder.append(" and a.enabled = 0 ");
        whereBuilder.append(" OR a.order_customer_status='DoneDelivery' ");
        whereBuilder.append(" OR a.order_customer_status='Done' )");
        whereBuilder.append(" ORDER BY a.createdTime DESC ");

    }




    public static String filedToLike(String filed){
        return   "%".concat(filed).concat("%");
    }
}
